//
//  AppManager.m
//  HealthKitDemo
//
//  Created by LZP on 2018/9/3.
//  Copyright © 2018年 鹏鹏. All rights reserved.
//

#import "AppManager.h"

@implementation AppManager

singleton_implementation(AppManager)

- (instancetype)init {
    if (self = [super init]) {
        NSString *dbPath = [self checkDBExits];
        self.dbQueue  = [FMDatabaseQueue databaseQueueWithPath:dbPath];
        self.dbQueue2 = [FMDatabaseQueue databaseQueueWithPath:dbPath];
        self.dbQueue3 = [FMDatabaseQueue databaseQueueWithPath:dbPath];
        [self checkTablesNeeded];
    }
    return self;
}

NSDateFormatter *timeFormatter(NSString *dateFormat) {
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    //设置UTC时间格式
    dateFormatter.dateFormat = dateFormat;
    return dateFormatter;
}
NSDateFormatter *defaultTimeFormatter(void) {
    return timeFormatter(@"yyyy-MM-dd HH:mm:ss.SSS");
}

NSString *currentDateString(void) {
    return [defaultTimeFormatter() stringFromDate:[NSDate date]];
}

NSString *databaseName(void) {
    return @"health.db";
}

- (void)checkTablesNeeded {
    // 先查查数据库在不在
    [self checkDBExits];
    // 创建单次记录表
    [self executeSQL:@"CREATE TABLE IF NOT EXISTS singleRecord (recordTime text, device text, count integer)" actionType:ST_DB_UPDATE withBlock:^(BOOL bRet, FMResultSet *rs, NSString *msg) {
        
    }];
    
    // 创建区间段表
    [self executeSQL:@"CREATE TABLE IF NOT EXISTS sectionRecord (startTime text, endTime text, count integer, updated integer)" actionType:ST_DB_UPDATE withBlock:^(BOOL bRet, FMResultSet *rs, NSString *msg) {
        
    }];
}

- (NSString *)checkDBExits {
    NSString *dbPath = [[self documentPath] stringByAppendingPathComponent:databaseName()];
    NSFileManager *fileManager = [NSFileManager defaultManager];
    BOOL dbExits = [fileManager fileExistsAtPath:dbPath];
    if (!dbExits) {
        // 创建咯
        [fileManager createFileAtPath:dbPath contents:nil attributes:nil];
    }
    NSLog(@"path: %@", dbPath);
    return dbPath;
}

- (NSString *)documentPath {
    return [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) firstObject];
}

- (void)deleteAllCaches {
    NSArray *array = @[@"delete from singleRecord", @"delete from sectionRecord"];
    [self executeSQLList:array withBlock:^(BOOL bRet, NSString *msg) {
        if (bRet) {
            NSLog(@"----清空表成功");
        }
    }];
}

- (void)addSingleRecordWithRecordTime:(NSString *)recordTime deviceName:(NSString *)deviceName count:(int)count completeHandler:(void (^)(BOOL))completeHandler {
    
    NSString *insertSR = [NSString stringWithFormat:@"insert into singleRecord(recordTime, device, count) values(\"%@\", \"%@\", %d)", recordTime, deviceName, count];
    NSLog(@"%@", insertSR);
    [self.dbQueue inDatabase:^(FMDatabase *db) {
        
        // 执行插入数据到单次记录表, 时间一样的也无所谓了, 只是记录
        BOOL ret = [db executeUpdate:insertSR];
        if ([db hadError]) {
            completeHandler(NO);
            NSLog(@"executeSQL error %d:  %@",[db lastErrorCode],[db lastErrorMessage]);
            return;
        }
        
        // 将本次操作时间提取出来
        // 初始化每个时间段的数据, 十分钟为一个分段
        // yyyy-MM-dd HH:mm:ss.SSS -> yyyy-MM-dd HH:m0:00 -> yyyy-MM-dd HH:m9:59
        // recordTime格式我们严格要求好的
        NSString *startTime = [NSString stringWithFormat:@"%@0:00", [recordTime substringToIndex:15]];
        NSString *endTime = [NSString stringWithFormat:@"%@9:59", [recordTime substringToIndex:15]];
        
        NSString *querySecR = [NSString stringWithFormat:@"select count from sectionRecord where startTime = \"%@\" and endTime = \"%@\"", startTime, endTime];
        NSLog(@"%@", querySecR);
        FMResultSet * rs = [db executeQuery:querySecR];
        int nCount = -1;
        if ([rs next]) {
            //获取查询数据的个数
            nCount = [rs intForColumn:@"count"];
        }
        [rs close];
        
        NSString * nextSqlString = nil;
        if (nCount >= 0) {
            //查询到了结果  执行update操作
            nextSqlString = [NSString stringWithFormat:@"update sectionRecord set count = %d where startTime = \"%@\"", nCount + count, startTime];
        }else{
            //查询无结果  执行 insert into 操作
            nextSqlString = [NSString stringWithFormat:@"insert into sectionRecord(startTime, endTime, count, updated) values(\"%@\", \"%@\", %d, %d)", startTime, endTime, count, 0];
        }
        NSLog(@"%@", nextSqlString);
        ret = [db executeUpdate:nextSqlString];
        completeHandler(YES);
    }];
}

- (void)queryAllSectRecordBeforeTime:(NSString *)currentTime WithStatus:(BOOL)updated completeHandler:(void (^)(NSArray<SectionRecordModel *> *))completeHandler {
    
    NSString *startTime = [NSString stringWithFormat:@"%@0:00", [currentTime substringToIndex:15]];
    NSString *sql = [NSString stringWithFormat:@"select startTime, endTime, count, updated from sectionRecord where updated = %d and startTime < \"%@\"", updated ? 1 : 0, startTime];
    dispatch_async(dispatch_get_global_queue(0, 0), ^{
        [self executeSQL:sql actionType:ST_DB_SELECT withBlock:^(BOOL bRet, FMResultSet *rs, NSString *msg) {
            if (bRet) {
                NSMutableArray *resultMArray = [NSMutableArray array];
                while ([rs next]) {
                    if (rs.resultDictionary.count > 0) {
                        SectionRecordModel *model = [SectionRecordModel yy_modelWithJSON:rs.resultDictionary];
                        [resultMArray addObject:model];
                    }
                }
                completeHandler([resultMArray copy]);
            } else {
                completeHandler(@[]);
            }
        }];
    });
}

- (void)updateSectionRecord:(SectionRecordModel *)model WithStatus:(BOOL)updated completeHandler:(void (^)(BOOL))completeHandler {

    NSString *sql = [NSString stringWithFormat:@"update sectionRecord set updated = %d where startTime = \"%@\"", updated ? 1 : 0, model.startTime];
    [self executeSQL:sql actionType:ST_DB_UPDATE withBlock:^(BOOL bRet, FMResultSet *rs, NSString *msg) {
        completeHandler(bRet);
    }];
}

- (void)queryDataFrom:(NSString *)startTime to:(NSString *)endTime status:(BOOL)updated completeHandler:(void (^)(NSArray<SectionRecordModel *> *))completeHandler {
    NSString *sql = [NSString stringWithFormat:@"select startTime, endTime, count, updated from sectionRecord where updated = %d and startTime >= \"%@\" and endTime <= \"%@\"", updated ? 1 : 0, startTime, endTime];
    dispatch_async(dispatch_get_global_queue(0, 0), ^{
        [self executeSQL:sql actionType:ST_DB_SELECT withBlock:^(BOOL bRet, FMResultSet *rs, NSString *msg) {
            if (bRet) {
                NSMutableArray *resultMArray = [NSMutableArray array];
                while ([rs next]) {
                    if (rs.resultDictionary.count > 0) {
                        SectionRecordModel *model = [SectionRecordModel yy_modelWithJSON:rs.resultDictionary];
                        [resultMArray addObject:model];
                    }
                }
                completeHandler([resultMArray copy]);
            } else {
                completeHandler(@[]);
            }
        }];
    });
}
@end
